#include <unistd.h>
#include <stdio.h>
#include <pthread.h>

int g_val = 1;

pthread_mutex_t g_lock;
pthread_cond_t p_cond;   // 生产者的队列
pthread_cond_t c_cond;   // 消费者的队列

//wait notify机制
void* Product(void* arg)
{
    while (true)
    {
        pthread_mutex_lock(&g_lock);

        while (g_val >= 1)
        {
            // 等待消费者消费完
            pthread_cond_wait(&p_cond, &g_lock);
        }

        g_val++;
        printf("Product done..:%d\n", g_val);

        pthread_mutex_unlock(&g_lock);

        // 通知消费者进行消费
        pthread_cond_signal(&c_cond);
    }
}

void* Consume(void* arg)
{
    while (true)
    {
        pthread_mutex_lock(&g_lock);

        while (g_val <= 0)
        {
            pthread_cond_wait(&c_cond, &g_lock);
        }
        g_val--;
        printf("Consume done..: %d\n", g_val);

        pthread_mutex_unlock(&g_lock);
        pthread_cond_signal(&p_cond);
    }
}

int main()
{
    pthread_t pt, ct;
    pthread_mutex_init(&g_lock, NULL);
    pthread_cond_init(&p_cond, NULL);
    pthread_cond_init(&c_cond, NULL);

    pthread_create(&pt, NULL, Product, NULL);
    pthread_create(&ct, NULL, Consume, NULL);

    pthread_join(pt, NULL);
    pthread_join(ct, NULL);

    pthread_mutex_destroy(&g_lock);
    pthread_cond_destroy(&p_cond);
    pthread_cond_destroy(&c_cond);

    return 0;
}